package top.mczhengyi.xyblog.auth;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.mczhengyi.xyblog.entity.Result;
import top.mczhengyi.xyblog.entity.ResultCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限认证
 */

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (requireLogin(handler)) {
            String token = request.getHeader("TOKEN");
            if (!AuthManage.check(token)) {
                // 创建错误的序列化
                String json = "";
                try {
                    json = objectMapper.writeValueAsString(Result.fail(ResultCode.NO_AUTH));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                response.setHeader("Content-Type", "application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(json);
                writer.flush();
                writer.close();
                return false;
            }
        }
        return true;
    }

    /**
     * 判断权限
     */
    private boolean requireLogin(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequireLogin requireLogin = handlerMethod.getMethod().getAnnotation(RequireLogin.class);
            if (requireLogin == null) {
                return false;
            }
            return true;
        }
        return false;
    }
}
